var currentUserId = "";
var currentUserName = "";
var currentCourseId = "";
var currentCourseYear= "";
var currentCourseName = "";
var currentAssignmentId = "";
var currentAssignmentName = "";
var currentActivityId = "";
var currentActivityName = "";
$(function(){
	$.ajax({
		url:'/pad/getSessionUser',
		success:function(user){
			currentUserId = user.id;
			currentUserName = user.realname;
			$("#user").html(user.realname+' <span class="caret"></span>');
		}
	});
	//groupListView(getQueryString("courseId"));
	$.ajax({
		url:'/pad/course/getCourse?courseId='+getQueryString("courseId"),
		success:function(course){
			currentCourseId = course.id;
			currentCourseYear= course.year;
			currentCourseName = course.courseName;
			courseListView();
		}
	});
});
/**
 * 获取url参数字符串
 * @param name
 * @returns
 */
function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	var groupid;
	if (r != null)
		return unescape(r[2]);
	return null;
}
/**
 * 提交表单
 */
function submitForm(formSelecter,modalSelecter){
	// 异步提交表单
    $(formSelecter).ajaxSubmit({  
        type:'post',
        resetForm: true,
        success:function(data){ 
        	$(modalSelecter).modal('hide');
        	location.reload();
        },
        error:function(msg){
        	alert(msg.statusText);
        }
    });  
}
/**
 * 发送get请求（用来删除记录后更新）
 */
function ajaxGet(url){
    $.ajax({
    	url:url,
    	success:function(data){ 
        	if(data=='success'){
        		$('#data-table').bootstrapTable('refresh');
        	}else{
        		alert(data);
        	}
        },
        error:function(msg){
        	alert(msg.statusText);
        }
    });
}
function groupListView(courseId){
	$('#breadcrumb').html('<li><a href="/pad">首页</a></li>');
	$('#toolbar').html('<button class="btn btn-info" data-toggle="modal" data-target="#createActivityModal"><span class="glyphicon glyphicon-plus"></span>创建活动</button>');
	$('#data-table').bootstrapTable('destroy');
	$('#data-table').bootstrapTable({
	    url: '/pad/course/getGroups?courseId='+courseId,
	    pagination:true,
	    search:true,
	    undefinedText:'',
	    striped:true,
	    showRefresh:true,
	    detailFormatter:function(index,row){
	    	var html = '';
	    	$.ajax({
	    		async: false,
	    		url:'/pad/course/getStudentsByGroupId?groupId='+row.id,
	    		success:function(data){
	    			var studentList = data.data;
	    			html += '<table class="table">';
	    			console.log(studentList);
	    			$.each(studentList, function(index, student){
    	                html += '<tr>';
    	                html += '<td>'+student.studentNum+'</td>';
    	                html += '<td>'+student.name+'</td>';
    	                html += '<td>'+student.groupNum+'</td>';
    	                html += '<td>'+student.commentGroupNum+'</td>';
    	                html += '<td>'+student.singleNum+'</td>';
    	                html += '<td>'+student.commentSingleNum+'</td>';
    	                html+="<td><a class='btn btn-warning btn-xs submitInfo' href='javascript:updateStudent(\""+getQueryString("courseId")+"\",\""+student.userId+"\",\""+student.studentNum+"\",\""+student.name+"\",\""+student.email+"\",\""+student.groupNum+"\",\""+student.commentGroupNum+"\",\""+student.singleNum+"\",\""+student.commentSingleNum+"\");'>修改</a> <a class='btn btn-error btn-xs' href='javascript:deleteStudent(\""+currentCourseId+"\",\""+student.userId+"\");'>删除</a></td>";
    	                html += '</tr>';
	    			});
	    			html += '</table>';
	    		}
	    	});
	    	return html;
	    },
	    toolbar:'#toolbar',
	    detailView:true,
	    idField:'id',
	    sortName:'startDate',
	    columns: [
	    	{field: 'groupNum',title: '小组号',width:100},
	    	{field: 'groupName',title: '小组名称'}]
	});	
}
function courseListView(){
	$('#breadcrumb').html('<li><a href="/pad">首页</a></li><li class="active">学生管理</li>');
	$("#student-table").before('<h2>课程：《'+currentCourseName+'》</h2><p><button class="btn btn-info" onclick=\'javascript:updateCourse("'+currentCourseId+'","'+currentCourseYear+'","'+currentCourseName+'");\'>添加新小组和学生</button></p>');
	$.ajax({
		url:'/pad/course/getStudents?courseId='+getQueryString("courseId"),
		success:function(data){
			var userInfo = data.data;
			var tableHtml = "";
			$.each(userInfo,function(index,user){
				tableHtml+="<tr>";
				tableHtml+="<td>"+user.studentNum+"</td>";
				tableHtml+="<td>"+user.name+"</td>";
				tableHtml+="<td>"+user.groupNum+"</td>";
				tableHtml+="<td>"+user.commentGroupNum+"</td>";
				tableHtml+="<td>"+user.singleNum+"</td>";
				tableHtml+="<td>"+user.commentSingleNum+"</td>";
				tableHtml+="<td>"+user.email+"</td>";
				tableHtml+="<td><a class='btn btn-warning btn-xs submitInfo' href='javascript:updateStudent(\""+getQueryString("courseId")+"\",\""+user.userId+"\",\""+user.studentNum+"\",\""+user.name+"\",\""+user.email+"\",\""+user.groupNum+"\",\""+user.commentGroupNum+"\",\""+user.singleNum+"\",\""+user.commentSingleNum+"\");'>修改</a> <a class='btn btn-danger btn-xs submitInfo' href='javascript:deleteStudent(\""+currentCourseId+"\",\""+user.userId+"\");'>删除</a></td>";
				tableHtml+="</tr>";
			});
			$("#student-table").append(tableHtml);
		}
	});
}
function updateCourse(id,year,courseName){
	$('#updateCourse input[name="id"]').val(id);
	$('#updateCourse input[name="year"]').val(year);
	$('#updateCourse input[name="courseName"]').val(courseName);
	$('#updateCourseModal').modal('show');
}
function deleteStudent(courseId,userId){
	$.ajax({
    	url:'/pad/course/deleteStudent?courseId='+courseId+'&userId='+userId,
    	success:function(data){ 
        	location.reload();
        },
        error:function(msg){
        	alert(msg.statusText);
        }
    });
}
function updateStudent(courseId,userId,studentNum,name,email,groupNum,commentGroupNum,singleNum,commentSingleNum){
	$('#updateStudent input[name="courseId"]').val(courseId);
$('#updateStudent input[name="userId"]').val(userId);
$('#updateStudent input[name="studentNum"]').val(studentNum);
$('#updateStudent input[name="name"]').val(name);
$('#updateStudent input[name="email"]').val(email);
$('#updateStudent input[name="groupNum"]').val(groupNum);
$('#updateStudent input[name="commentGroupNum"]').val(commentGroupNum);
$('#updateStudent input[name="singleNum"]').val(singleNum);
$('#updateStudent input[name="commentSingleNum"]').val(commentSingleNum);
$('#updateStudentModal').modal('show');
}
function assignmentListView(courseId,courseName){
	manageConst(courseId,courseName);
	$('input[name="courseId"]').val(courseId);
$('#breadcrumb').html('<li><a href="/pad">首页</a></li><li><a href="javascript:courseListView();">课程列表</a></li><li class="active">'+courseName+'</li>');
$('#toolbar').html('<button class="btn btn-info" data-toggle="modal" data-target="#createAssignmentModal"><span class="glyphicon glyphicon-plus"></span>创建作业</button>');
$('#data-table').bootstrapTable('destroy');
$('#data-table').bootstrapTable({
    url: 'assignment/getAssignments?courseId='+courseId,
    pagination:true,
    search:true,
    undefinedText:'',
    striped:true,
    showRefresh:true,
    toolbar:'#toolbar',
    // detailView:true,
    idField:'id',
    columns: [
    	{field: 'assignmentName',title: '作业名称'},
    	{field: 'description',title: '作业描述'},
    	{field: 'startDate',title: '开始时间',width:100},
    	{field: 'endDate',title: '结束时间',width:100},
    	{field: 'op',title: '操作',width:150,formatter:function(value,row,index){
    		return '<a href="javascript:activityListView(\''+row.id+'\',\''+row.assignmentName+'\',\''+row.startDate+'\',\''+row.endDate+'\');" class="btn btn-info btn-xs">进入</a> '+"<a href='javascript:updateAssignment("+JSON.stringify(row)+");' class='btn btn-warning btn-xs'>修改</a>"+' <a href="javascript:ajaxGet(\'/pad/assignment/deleteAssignment?assignmentId='+row.id+'\');" class="btn btn-danger btn-xs">删除</a>';
	    	}}]
	});
}
function updateAssignment(row){
	$('#updateAssignment input[name="id"]').val(row.id);
$('#updateAssignment input[name="assignmentName"]').val(row.assignmentName);
$('#updateAssignment select[name="assignmentType"]').selectpicker('val', row.assignmentType);
$('#updateAssignment textarea[name="description"]').val(row.description);
$('#updateAssignment textarea[name="assignmentContent"]').val(row.assignmentContent);
$('#updateAssignment input[name="startDate"]').val(row.startDate);
$('#updateAssignment input[name="endDate"]').val(row.endDate);
$('#updateAssignmentModal').modal('show');
}
function activityListView(assignmentId,assignmentName,startDate,endDate){
	manageConst(currentCourseId,currentCourseName,assignmentId,assignmentName);
	$('input[name="assignmentId"]').val(assignmentId);
console.log(startDate + " " +new Date(startDate).format('yyyy-MM-dd'));
$('#createActivityModal').find('.date-start').datetimepicker('setStartDate',new Date(startDate).format('yyyy-MM-dd'));
$('#createActivityModal').find('.date-start').datetimepicker('setEndDate',new Date(endDate).format('yyyy-MM-dd'));
$('#createActivityModal').find('.date-end').datetimepicker('setEndDate',new Date(endDate).format('yyyy-MM-dd'));
$('#breadcrumb').html('<li><a href="/pad">首页</a></li><li><a href="javascript:courseListView();">课程列表</a></li><li><a href="javascript:assignmentListView(\''+currentCourseId+'\',\''+currentCourseName+'\');">'+currentCourseName+'</a></li><li class="active">'+assignmentName+'</li>');
$('#toolbar').html('<button class="btn btn-info" data-toggle="modal" data-target="#createActivityModal"><span class="glyphicon glyphicon-plus"></span>创建活动</button>');
$('#data-table').bootstrapTable('destroy');
$('#data-table').bootstrapTable({
    url: 'activity/getActivities?assignmentId='+assignmentId,
    pagination:true,
    search:true,
    undefinedText:'',
    striped:true,
    showRefresh:true,
    detailFormatter:function(index,row){
    	var html = '';
    	$.ajax({
    		async: false,
    		url:'/pad/activity/getActivityGroupVisions?activityId='+row.id,
    		success:function(activityGroupVisionList){
    			html += '<table class="table">';
    			html+='<tr><td></td><td><button style="margin-right:10px;" onclick="selectValue(this.value)" value="1" id="selectAll1" class="btn btn-warning btn-xs" >全选折线图</button><button id="selectAll2" onclick="selectValue(this.value)" value="2" style="margin-right:10px;" class="btn btn-warning btn-xs" >全选数字饼图</button><button id="selectAll3" onclick="selectValue(this.value)" value="3" style="margin-right:10px;" class="btn btn-warning btn-xs" >全选版本数柱状图</button><button id="selectAll4" onclick="selectValue(this.value)" value="4" style="margin-right:10px;" class="btn btn-warning btn-xs" >全选组内互评雷达图</button><button id="selectAll5" onclick="selectValue(this.value)" value="5" style="margin-right:10px;" class="btn btn-warning btn-xs" >全选组内互评社会网络图</button><button id="selectAll6" onclick="selectValue(this.value)" value="6" style="margin-right:10px;" class="btn btn-warning btn-xs" >全选组间互评雷达图</button><button id="selectAll7" onclick="selectValue(this.value)" value="7" style="margin-right:10px;" class="btn btn-warning btn-xs" >全选组间互评社会网络图</button><button id="saveAll" style="margin-right:10px;" type="button" onclick="saveAllInfo()" class="btn btn-warning btn-xs" >全部保存</button></td></tr>';
    			html+='<tr><td></td><td><button style="margin-right:10px;" onclick="unSelectValue(this.value)" value="1" id="selectAll1" class="btn btn-warning btn-xs" >不选折线图</button><button id="selectAll2" onclick="unSelectValue(this.value)" value="2" style="margin-right:10px;" class="btn btn-warning btn-xs" >不选数字饼图</button><button id="selectAll3" onclick="unSelectValue(this.value)" value="3" style="margin-right:10px;" class="btn btn-warning btn-xs" >不选版本数柱状图</button><button id="selectAll4" onclick="unSelectValue(this.value)" value="4" style="margin-right:10px;" class="btn btn-warning btn-xs" >不选组内互评雷达图</button><button id="selectAll5" onclick="unSelectValue(this.value)" value="5" style="margin-right:10px;" class="btn btn-warning btn-xs" >不选组内互评社会网络图</button><button id="selectAll6" onclick="unSelectValue(this.value)" value="6" style="margin-right:10px;" class="btn btn-warning btn-xs" >不选组间互评雷达图</button><button id="selectAll7" onclick="unSelectValue(this.value)" value="7" style="margin-right:10px;" class="btn btn-warning btn-xs" >不选组间互评社会网络图</button></td></tr>';
    			$.each(activityGroupVisionList, function(index, activityGroupVision){
	                html += '<tr>';
	                html += '<td>'+activityGroupVision.groupName+'</td>'
	                html += '<td><form class="rowForm" action="activity/saveActivityGroupVision" method="post"><input type="hidden" name="id" value="'+activityGroupVision.id+'"/><input type="hidden" name="activityId" value="'+activityGroupVision.activityId+'"/><input type="hidden" name="groupId" value="'+activityGroupVision.groupId+'"/><input type="hidden" name="groupName" value="'+activityGroupVision.groupName+'"/><input type="hidden" name="groupType" value="'+activityGroupVision.groupType+'"/>';
	                /*
	                $.ajax({
	    	    		async: false,
	    	    		url:'getDictionary?code=VISION',
	    	    		success:function(dictionaryList){
	    	    			$.each(dictionaryList, function(index, dictionary){
	    	    				var vision_n = activityGroupVision.vision==null?"":activityGroupVision.vision;
	    	    				if(vision_n.indexOf(dictionary.dictTitle)>-1)
	    	    					html += ' <input name="vision" checked type="checkbox" value="'+dictionary.dictTitle+'" />'+dictionary.dictText;
	    	    				else
	    	    					html += ' <input name="vision" type="checkbox" value="'+dictionary.dictTitle+'" />'+dictionary.dictText;
	    	    			});
	    	    		}
	                });
    	                */
    	                html+='<input name="vision" type="checkbox" value="1" />&nbsp专注度折线图 &nbsp';
    	                
    	                html+='<input name="vision" type="checkbox" value="2" />&nbsp字数饼图 &nbsp';

    	                html+='<input name="vision" type="checkbox" value="3" />&nbsp版本数柱状图 &nbsp';

    	                html+='<input name="vision" type="checkbox" value="4" />&nbsp组内互评雷达图 &nbsp';

    	                html+='<input name="vision" type="checkbox" value="5" />&nbsp组内互评社会网络图 &nbsp';
    	               
    	                html+='<input name="vision" type="checkbox" value="6" />&nbsp组间互评雷达图 &nbsp';
    	                
    	                html+='<input name="vision" type="checkbox" value="7" />&nbsp组间互评社会网络图 &nbsp';

    	                html += '</select>';
    	                html += '<button type="button" class="btn btn-warning btn-xs submitInfo" onclick="submitSaveActivityGroupVisionForm(this);">保存</button>';
    	                html += '</form></td></tr>';
	    			});
	    			html += '</table>';
	    		}
	    	});
	    	return html;
	    },
	    toolbar:'#toolbar',
	    detailView:true,
	    idField:'id',
	    sortName:'startDate',
	    rowStyle:function rowStyle(row, index) {
	    	if(new Date(row.startDate)>new Date()){
	    		return {
					css: {"color": "#fff","background-color": "#bcd2d8"}
				};
    		}else if(new Date(row.startDate)<new Date() &&　new Date(row.endDate)>new Date()){
    			return {
					css: {"color": "#fff","background-color": "#6de66b"}
				};
    		}else{
    			return {
					css: {"color": "#fff","background-color": "#bbb"}
				};
    		}
	    	
		},
	    columns: [
	    	{field: 'activityType',title: '活动状态',width:100,formatter:function(value,row,index){
	    		if(new Date(row.startDate)>new Date()){
	    			return '即将开始';
	    		}else if(new Date(row.startDate)<new Date() &&　new Date(row.endDate)>new Date()){
	    			return '正在进行';
	    		}else{
	    			return '已结束';
	    		}
	    	}},
	    	{field: 'activityName',title: '活动名称'},
	    	{field: 'description',title: '活动描述'},
	    	{field: 'startDate',title: '开始时间',width:100},
	    	{field: 'endDate',title: '结束时间',width:100},
	    	{field: 'op',title: '操作',width:100,formatter:function(value,row,index){
	    		return "<a href='javascript:updateActivity("+JSON.stringify(row)+");' class='btn btn-warning btn-xs'>修改</a> <a href='javascript:ajaxGet(\"/pad/activity/deleteActivity?activityId="+row.id+"\");' class='btn btn-danger btn-xs'>删除</a>";
	    	}}]
	});	
}
function submitSaveActivityGroupVisionForm(dom){
	// 异步提交表单
    $(dom).parent('form').ajaxSubmit({  
        type:'post',
        success:function(data){
        	if(data=='success'){
        		console.log(data);
        	}else{
        		alert(data);
        		$('#data-table').bootstrapTable('refresh');
        	}
        },
        error:function(msg){
        	alert(msg.statusText);
        }
    });  
}
function updateActivity(row){
	$('#updateActivity input[name="id"]').val(row.id);
	$('#updateActivity input[name="activityName"]').val(row.activityName);
	$('#updateActivity input[name="description"]').val(row.description);
	$('#updateActivity select[name="activityType"]').selectpicker('val', row.activityType);
	$('#updateActivity input[name="startDate"]').val(row.startDate);
	$('#updateActivity input[name="endDate"]').val(row.endDate);
	$('#updateActivity select[name="commentTemplateId"]').selectpicker('val', row.commentTemplateId);
	$('#updateActivityModal').modal('show');
}

$(function(){
    /**
	 * 时间对象的格式化;
	 */  
    Date.prototype.format = function(format) {  
        /*
		 * eg:format="yyyy-MM-dd hh:mm:ss";
		 */  
        var o = {  
            "M+" : this.getMonth() + 1, // month
            "d+" : this.getDate(), // day
            "h+" : this.getHours(), // hour
            "m+" : this.getMinutes(), // minute
            "s+" : this.getSeconds(), // second
            "q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
            "S" : this.getMilliseconds()  
            // millisecond
        }  
      
        if (/(y+)/.test(format)) {  
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));  
        }  
        for (var k in o) {  
            if (new RegExp("(" + k + ")").test(format)) {  
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));  
            }  
        }  
        return format;  
    }  
});
function selectValue(value){
	$('input[value=\"'+value+'\"]').prop("checked",true);
}
function unSelectValue(value){
	$('input[value=\"'+value+'\"]').prop("checked",false);
}
function saveAllInfo(){
	$('.submitInfo').trigger('click');
}
